/**
 * 数据库连接配置
 * 
 * 主要功能：
 * - 创建MySQL数据库连接池
 *
 * @file connection.js
 * @version 1.0.0
 * @author "nailuo"
 * @created 2025-8-30
 * @lastModified 2025-8-30
 */

require('dotenv').config();
const mysql = require('mysql2/promise');

// 创建连接池
const pool = mysql.createPool({
    host: process.env.db_host || 'localhost',
    port: process.env.db_port || 3306,
    user: process.env.db_user || 'root',
    password: process.env.db_password || '',
    database: process.env.db_name,
    waitForConnections: true,
    connectionLimit: process.env.db_connection_limit || 10,
});


// 测试数据库连接
const testConnection = async () => {
    try {
        const connection = await pool.getConnection();
        console.log('✅ 数据库连接成功');
        connection.release();
        return true;
    } catch (error) {
        console.error('❌ 数据库连接失败:', error.message);
        throw error.message;
    }
};

// 关闭数据库连接
const closeConnection = async () => {
    try {
        await pool.end();
        console.log('✅ 数据库连接已关闭');
    } catch (error) {
        console.error('❌ 关闭数据库连接失败:', error.message);
        throw error.message;
    }
};

// 导出模块
module.exports = {
    pool,
    testConnection,
    closeConnection,
};